package com.itboye.jinpuyiyuan.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.widget.ImageView;

import com.itboye.jinpuyiyuan.R;
import com.itboye.jinpuyiyuan.app.MyApplication;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;




/**
 * Created by itboye on 2017/3/7.
 */

public class XImageLoader {
    static {
        long maxMamory = Runtime.getRuntime().maxMemory();// 应用程序程序运行时所使用最大内存数
        maxMamory = (long) (maxMamory * 0.7);
        int v = Runtime.getRuntime().availableProcessors();
        int availableProcessors = v < 4 ? 4 : v;

        DisplayImageOptions options = new DisplayImageOptions.Builder()
                // 设置图片下载期间显示的图片
                .showImageOnLoading(R.mipmap.ic_launcher).showImageForEmptyUri(R.mipmap.ic_launcher)// 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.login_logo) // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true)// 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)// 设置下载的图片是否缓存在SD卡中
                .bitmapConfig(Bitmap.Config.RGB_565)
                // .displayer(new RoundedBitmapDisplayer(20))// 设置成圆角图片
                .build(); // 创建配置过得DisplayImageOption对象 

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(MyApplication.getInstance())
                .memoryCacheExtraOptions(480, 800) // max width, max
                // height，即保存的每个缓存文件的最大长宽
                // .discCacheExtraOptions(480, 800, CompressFormat.JPEG, 75,
                // null) // Can slow ImageLoader, use it carefully (Better don't
                // use it)/设置缓存的详细信息，最好不要设置这个
                .threadPoolSize(availableProcessors)// 线程池内加载的数量
                .threadPriority(Thread.NORM_PRIORITY).denyCacheImageMultipleSizesInMemory()
                // .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 *
                // 1024)) // You can pass your own memory cache
                // implementation/你可以通过自己的内存缓存实现
                // .memoryCache(new WeakMemoryCache())

                .memoryCacheSize((int) maxMamory)
                // .memoryCacheSize(15 * 1024 * 1024)

                .diskCacheSize(80 * 1024 * 1024).diskCacheFileNameGenerator(new Md5FileNameGenerator())// 将保存的时候的URI名称用MD5
                // 加密

                .tasksProcessingOrder(QueueProcessingType.LIFO) // 后进先出
                // .diskCacheFileCount(100) //缓存的文件数量
                // .diskCache(new UnlimitedDiscCache(cacheDir))//自定义缓存路径
                // .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
                .defaultDisplayImageOptions(options)
                // .imageDownloader(new BaseImageDownloader(App.ctx, 5 * 1000,
                // 30 * 1000)) // connectTimeout (5 s), readTimeout (30 s)超时时间
                .imageDownloader(new DownloadImageFromNetWork(MyApplication.getInstance(), 5 * 1000, 30 * 1000)).writeDebugLogs() // Remove
                // for
                // release
                // app
                .build();// 开始构建
        // Initialize ImageLoader with configuration.

        com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(config);// 全局初始化此配置

    }

    private static class DownloadImageFromNetWork extends BaseImageDownloader {

        public DownloadImageFromNetWork(Context context, int connectTimeout, int readTimeout) {
            super(context, connectTimeout, readTimeout);
        }

        @Override
        protected InputStream getStreamFromNetwork(String arg0, Object arg1) throws IOException {

            try {
                OkHttpClient client = new OkHttpClient();
                client.setConnectTimeout(connectTimeout, TimeUnit.MILLISECONDS);
                client.setReadTimeout(readTimeout, TimeUnit.MILLISECONDS);
                Request request = new Request.Builder().url(arg0).build();
                Response response = client.newCall(request).execute();
                if (!response.isSuccessful()) {
                    return null;
                } else {
                    return response.body().byteStream();
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            }
        }

    }

    public static void load(String uri, ImageView imageView) {

        ImageLoader.getInstance().displayImage(uri, imageView);

    }
    public static Bitmap loadBitmap(String uri){
        return ImageLoader.getInstance().loadImageSync(uri);
    }
}
